package cn.com.czpb.client.module.news.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.MToolBarActivity;
import cn.com.czpb.client.custorm.CircleImageView;
import cn.com.czpb.client.custorm.DonutProgress;
import cn.com.czpb.client.custorm.TouchImageView;
import cn.com.czpb.client.model.event.PraiseEvent;
import cn.com.czpb.client.model.news.AlbumDetailEntity;
import cn.com.czpb.client.model.news.EmptyEntityList;
import cn.com.czpb.client.model.news.ImageListSubBean;
import cn.com.czpb.client.model.news.ImgListBean;
import cn.com.czpb.client.model.news.IsCollectionEntity;
import cn.com.czpb.client.model.news.NewsDetailBean;
import cn.com.czpb.client.model.news.NewsDetailEntity;
import cn.com.czpb.client.model.news.PraiseNumEntity;
import cn.com.czpb.client.model.usercenter.LevelEntity;
import cn.com.czpb.client.module.dialog.ShareDialog;
import cn.com.czpb.client.module.news.adapter.RecyclingPagerAdapter;
import cn.com.czpb.client.module.personal.WodeFragment;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;
import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/7/5.
 */

public class NewsAlbum_Activity extends MToolBarActivity {


    @BindView(R.id.img_detail_test_pager)
    ViewPager mViewPager;
    @BindView(R.id.img_detail_title_id)
    TextView mTextViewTitle;
    @BindView(R.id.img_detail_content_id)
    TextView mTextViewContent;
    @BindView(R.id.img_detial_number_id)
    TextView mTextViewNumber;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_creator)
    TextView tv_creator;
    @BindView(R.id.album_donutProgress)
    DonutProgress donutProgress;
    @BindView(R.id.img_pic_id)
    CircleImageView img_pic_id;//创建人

    @BindView(R.id.img_detail_title)
    RelativeLayout imgDetailTitle;

    @BindView(R.id.img_back)
    LinearLayout imgBack;
    @BindView(R.id.img_comment)
    ImageView imgComment;
    @BindView(R.id.ll_newdetail_comments)
    LinearLayout llNewdetailComments;
    @BindView(R.id.img_praise)
    ImageView imgPraise;
    @BindView(R.id.praise_number_tx)
    TextView praiseNumberTx;
    @BindView(R.id.ll_newdetail_praise)
    LinearLayout llNewdetailPraise;
    @BindView(R.id.img_collection)
    ImageView imgCollection;
    @BindView(R.id.collection_number_tx)
    TextView collectionNumberTx;
    @BindView(R.id.ll_newdetail_collection)
    LinearLayout llNewdetailCollection;
    @BindView(R.id.img_share)
    ImageView imgShare;
    @BindView(R.id.share_number_tx)
    TextView shareNumberTx;
    @BindView(R.id.ll_newdetail_share)
    LinearLayout llNewdetailShare;
    @BindView(R.id.news_detail_ll_bottom1)
    LinearLayout newsDetailLlBottom1;
    @BindView(R.id.ll_back_1)
    LinearLayout llBack1;
    @BindView(R.id.comment_number_tx)
    TextView commentNumberTx;


    private NewsAlbumAdapter simpleAdapter;

    private String from;//news album newsitem
    private int currentPosition = 0;

    @BindView(R.id.album_rl_head)
    RelativeLayout album_rl_head;//头部
    @BindView(R.id.album_rl_bottom)//底部
            RelativeLayout album_rl_bottom;

    private boolean animationFlag = false;//是否隐藏

    private NewsDetailBean ndb;
    private ImgListBean imgListBean;
    private ArrayList<String> images;

    private String rvalue;
    private String nid;
    @Override
    public int setLayoutId() {
        return R.layout.news_detail_img_main_layout;
    }

    @Override
    public void initView() {
        mImmersionBar.statusBarDarkFont(true);
//        setToolBarVisiable(false);
        String pid = null;
        Intent intent = getIntent();

        String action = intent.getAction();
        if (null != action && Intent.ACTION_VIEW.equals(action)) {
            Uri uri = intent.getData();
            if (uri != null) {
                pid = uri.getPath();
                pid = pid.replace(File.separator, "");
                from = "browser";
//                getAlbum_browser(pid);
            }
        } else {
            from = intent.getStringExtra("from");
        }

        initViewPage();

        if ("news".equals(from)) {
            images = intent.getStringArrayListExtra("imags");
            currentPosition = intent.getIntExtra("position", 0);
//            ndb = (NewsDetailBean) intent.getSerializableExtra("ndb");

            List<ImageListSubBean> mlist = new ArrayList<ImageListSubBean>();
//			if(null!=ndb.getImgs()){
            for (String im : images) {
                ImageListSubBean ilsb = new ImageListSubBean("", im);
                mlist.add(ilsb);
            }
            simpleAdapter.setList(mlist);
//			}
            try {
                mTextViewTitle.setText(imgListBean.getTitle());
            } catch (Exception e) {

            }

            if (simpleAdapter.getCount() > currentPosition) {
                mViewPager.setCurrentItem(currentPosition);
            }
        } else if ("album".equals(from)) {
            currentPosition = 0;
            imgListBean = (ImgListBean) intent.getSerializableExtra("imgbean");
            if (null != imgListBean) {
                simpleAdapter.setList(imgListBean.getSubphoto());
            }
        } else {
            rvalue = intent.getStringExtra("rvalue");
            nid = intent.getStringExtra("nid");
            LogUtils.e("nid---" + nid + rvalue);
            //获取图集
            getAlbum_ni(rvalue);
            getNewsDetails(nid);
        }
    }
    //添加浏览量
    public void addVisits(String tid) {
        Map<String, String> map = new HashMap<>();
        map.put("nid", nid);
        map.put("type", "2");
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("num", "1");
        map.put("tid", tid);
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        map.put("device", DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService().addvisit(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntityList, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntityList emptyEntityList) {
                        return true;
                    }
                })

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntityList>() {
                    @Override
                    public void call(EmptyEntityList emptyEntityList) {
                        LogUtils.i("emptyEntityList----" + emptyEntityList.code);
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }

    private void getNewsDetails(String nid) {
        LogUtils.i("nid-->" + nid);
        Map<String, String> map = new HashMap<>();
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        map.put("nid", nid);
        Factory.provideHttpService()
                .newsDetail(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsDetailEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsDetailEntity entity) {
                        LogUtils.i("detail-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsDetailEntity>() {
                    @Override
                    public void call(NewsDetailEntity entity) {
                        //添加浏览量
                        addVisits(entity.data.getTid());
                        ndb = entity.data;
                        commentNumberTx.setText(ndb.getComcount());
                        praiseNumberTx.setText(ndb.getPraisecount());
                        collectionNumberTx.setText(ndb.getFavoritecount());
                        if ("1".equals(entity.data.getIsfavorite())) {
                            imgCollection.setImageResource(R.drawable.tabbar_collect_light);
                        } else {
                            imgCollection.setImageResource(R.drawable.tabbar_collect);
                        }
                        if ("1".equals(entity.data.getIspraise())) {
                            imgPraise.setImageResource(R.drawable.tabbar_like_light);
                        } else {
                            imgPraise.setImageResource(R.drawable.tabbar_like);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("detail-->throwable-->" + throwable);
                    }
                });
    }

    private void setNewsData() {
        commentNumberTx.setText(ndb.getComcount());
        praiseNumberTx.setText(ndb.getPraisecount());
        collectionNumberTx.setText(ndb.getFavoritecount());
    }


    private void initViewPage() {
        simpleAdapter = new NewsAlbumAdapter();

//        mViewPager.setPageMargin(10);

        mViewPager.setAdapter(simpleAdapter);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrollStateChanged(int arg0) {

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageSelected(int arg0) {
                mTextViewNumber.setText((arg0 + 1) + "/" + simpleAdapter.getCount());
                mTextViewContent.setText(simpleAdapter.getDes(arg0));
                currentPosition = arg0;
            }
        });
        mViewPager.setCurrentItem(currentPosition);

    }

    @OnClick({R.id.img_back, R.id.ll_newdetail_comments, R.id.ll_newdetail_praise, R.id.ll_newdetail_collection, R.id.ll_newdetail_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                this.finish();
                break;
            case R.id.ll_newdetail_collection:
                if (spu.getUser() != null) {
                    addCollection();
                } else {
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.ll_newdetail_share:
                if(spu.getUser() != null) {
                    String link = ndb.getNewsurl()+ "/uid/" + spu.getUser().getUid();
                    ShareDialog shareDialog = new ShareDialog(activity, R.style.Sharedialog, ndb.getTitle(), link, ndb.getImgs().get(0), 1);
                    shareDialog.show();
                }else{
                    TUtils.toast("请先登录！");
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.ll_newdetail_comments:
                if (spu.getUser() != null) {
                    PageCtrl.startCommActivity(activity, nid, "2", "ALBUM", rvalue, ndb);
                } else {
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.ll_newdetail_praise:
                praiseContent();
                break;
        }
    }

    //赞
    private void praiseContent() {
        Map<String, String> map = new HashMap<>();
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        map.put("device", DeviceUtils.getMyUUID(activity));
        map.put("nid", ndb.getNid());
        map.put("tid", ndb.getTid());
        map.put("type", ndb.getRtype());
        map.put("siteid", "1");
        Factory.provideHttpService().praiseContent(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<PraiseNumEntity>() {
                    @Override
                    public void call(PraiseNumEntity baseEntity) {

                        if ("200".equals(baseEntity.code)) {
                            imgPraise.setImageResource(R.drawable.tabbar_like_light);
                            praiseNumberTx.setText(baseEntity.data.getPraisecount());
                            PraiseEvent praiseEvent = new PraiseEvent();
                            praiseEvent.setNid(ndb.getNid());
                            praiseEvent.setPraisecount(baseEntity.data.getPraisecount());
                            EventBus.getDefault().post(praiseEvent);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });

    }

    // 添加收藏
    private void addCollection() {
        Map<String, String> map = new HashMap<>();
        map.put("typeid", nid);
        map.put("uid", spu.getUser().getUid());
        map.put("type", "2");
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsAddCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)) {
                            if ("1".equals(entity.data.getStatus())) {
                                TUtils.toast("收藏成功");
                                initlevel();
                                imgCollection.setImageResource(R.drawable.tabbar_collect_light);
                                collectionNumberTx.setText(entity.data.getFavcount());
                            } else {
                                imgCollection.setImageResource(R.drawable.tabbar_collect);
                                collectionNumberTx.setText(entity.data.getFavcount());
                                TUtils.toast("收藏取消");
                            }
                        } else {
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }

    private void initlevel() {
        String uid = spu.getUser().getUid();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        Factory.provideHttpService().MyLevel(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<LevelEntity, Boolean>() {
                    @Override
                    public Boolean call(LevelEntity levelEntity) {

                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LevelEntity>() {
                    @Override
                    public void call(LevelEntity levelEntity) {
                        LogUtils.e("code--" + levelEntity.code);
                        if ("200".equals(levelEntity.code)) {
                            spu.getUser().setUlevel("Lv" + levelEntity.data.getUserinfo().getLevel());
                            Intent intent = new Intent();
                            intent.setAction(WodeFragment.ACTION_USER);
                            activity.sendBroadcast(intent);

                        } else {
                            TUtils.toast(levelEntity.msg);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.e("throwable------" + throwable.getMessage());
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    class NewsAlbumAdapter extends RecyclingPagerAdapter {
        //        @BindBitmap(R.id.pdv_img)
//        PhotoDraweeView pdvImg;
        private List<ImageListSubBean> list;
        private LayoutInflater inflater;

        public NewsAlbumAdapter() {

            list = new ArrayList<ImageListSubBean>();
            inflater = LayoutInflater.from(activity);

        }

        public ImageListSubBean getCurrentBean(int position) {
            return list.get(position % list.size());
        }

        public void setList(List<ImageListSubBean> mList) {
            if (mList.size() > 0) {
                clearList();
                addList(mList);
            }
        }

        public int getListSize() {
            return list.size();
        }

        public void addList(List<ImageListSubBean> mList) {
            list.addAll(mList);
            mTextViewNumber.setText("1/" + list.size());

            if ("news".equals(from)) {
//				imgdetails_title_pl.setVisibility(View.GONE);
                mTextViewTitle.setText(imgListBean.getTitle());

            } else {
                try {
                    mTextViewTitle.setText(imgListBean.getTitle());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (list.size() > 0) {
                mTextViewContent.setText(list.get(0).getSubdesc());
            }
            notifyDataSetChanged();
        }

        public void clearList() {
            list.clear();
        }

        @Override
        public int getCount() {
            return list.size();
        }

        public String getDes(int positon) {
            return list.get(positon).getSubdesc();
        }


        @Override
        public View getView(int position, View convertView, ViewGroup container) {
//            View view = inflater.inflate(R.layout.album_item, container, false);
            TouchImageView imgview = new TouchImageView(activity);
//            imgview = (TouchImageView)view.findViewById(R.id.pdv_img);
            Glide.with(activity).load(list.get(position).getSubphoto()).crossFade().placeholder(R.drawable.default_bg).into(imgview);
            return imgview;
        }
    }

    //获取单个图集
    private void getAlbum_ni(String nid) {
        Map<String, String> map = new HashMap<>();
        if(spu.getUser() != null){
            map.put("uid",spu.getUser().getUid());
        }
        map.put("pid", nid);
        map.put("device", DeviceUtils.getMyUUID(activity));
        LogUtils.i("pid-->" + nid);
        Factory.provideHttpService()
                .albumDetail(map)
                .subscribeOn(Schedulers.io())
                .filter(new Func1<AlbumDetailEntity, Boolean>() {
                    @Override
                    public Boolean call(AlbumDetailEntity entity) {
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<AlbumDetailEntity>() {
                    @Override
                    public void call(AlbumDetailEntity entity) {
                        LogUtils.e("图集---" + entity.data.getCreator_headimg());
                        currentPosition = 0;
                        imgListBean = entity.data;
                        simpleAdapter.setList(entity.data.getSubphoto());
                        commentNumberTx.setText(entity.data.getComcount());
                        Glide.with(activity).load(entity.data.getCreator_headimg()).into(img_pic_id);
                        commentNumberTx.setText(entity.data.getComcount());
                        tv_creator.setText(entity.data.getCreator());
                        tv_time.setText(entity.data.getCreate_time());
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable-->" + throwable.toString());
                        TUtils.toast("获取图集失败");
                        finish();
                    }
                });
    }

    @Override
    public void initData() {
    }

}
